package com.example.sourcecodelearning.spring.resource;

import lombok.SneakyThrows;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 资源加载器，用于读取配置文件生成Bean名称和类的映射关系
 */
public class ResourceLoader {

    /**
     * 扫描配置文件，建立BeanName-BeanClass的映射Map
     *
     * @return BeanName-BeanClass的映射Map
     */
    @SneakyThrows
    public static Map<String, BeanDefinition> getResource() {
        Map<String, BeanDefinition> beanDefinationMap = new HashMap<>();
        try (InputStream inputStream = ResourceLoader.class.getResourceAsStream("/beans.properties")) {
            Properties properties = new Properties();
            properties.load(inputStream);
            for (String beanName : properties.stringPropertyNames()) {
                Class<?> beanClass = Class.forName(properties.getProperty(beanName));
                BeanDefinition beanDefinition = new BeanDefinition()
                        .setBeanName(beanName)
                        .setBeanClass(beanClass);
                beanDefinationMap.put(beanName, beanDefinition);
            }
        }
        return beanDefinationMap;
    }
}
